package com.neusoft.javafeatures9.juc;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * .applyToEither().acceptEither().runAfterEither()
 * 三个：谁快用谁的方法
 * @author dva
 */
public class CompletetableFutureDemo2Either {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "---come in ");
            //暂停几秒钟线程
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("completableFuture1  完成");
            return 10;
        });

        CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "---come in ");
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("completableFuture2  完成");
            return 20;
        });

       //applyToEither 谁快用谁的取值，作为fn的入参
        /*CompletableFuture<Integer> thenCombineResult = completableFuture1.applyToEither(completableFuture2, f -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "---come in ");
            return f + 1;
        });
        */

        //acceptEither 谁快用谁的取值，作为fn的入参
        /*CompletableFuture<Void> thenCombineResult = completableFuture1.acceptEither(completableFuture2, f -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "---come in ");
            System.out.println("取到的值：" + f);
        });*/

        //runAfterEither 谁快用谁的取值，作为fn的入参
        CompletableFuture<Void> thenCombineResult = completableFuture1.runAfterEither(completableFuture2,
                () -> System.out.println(Thread.currentThread().getName() + "\t" + "---come in " + "runAfterEither..."));

        System.out.println(Thread.currentThread().getName() + "\t" + thenCombineResult.get());
    }
}
